import socket
import os
import struct


def send_file(filepath: str, sock: socket):
    try:
        if os.path.isfile(filepath):
            fileinfo_size = struct.calcsize('!128sl')  # ��128��str, 1��long
            fhead = struct.pack('!128sl', os.path.basename(filepath).encode('utf-8'),
                                os.stat(filepath).st_size)
            sock.send(fhead)
            fp = open(filepath, 'rb')
            while 1:
                data = fp.read(1024)
                if not data:
                    print('{0} file sent'.format(os.path.basename(filepath)))
                    break
                sock.send(data)
            return True
        else:
            print("Invalid filename")
            return False
    except Exception as e:
        print("Error when sending file: " + str(e))
        return False
